import React, { Fragment } from 'react'
import {
  View,
  StyleSheet,
  Text,
  ScrollView
} from 'react-native'
import { ScaleS, ScaleT, ONE_PIXEL } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import NextButton from 'src/components/button/NextButton'
import CustomButton from 'src/components/button/CustomButton'
import CustomImage from 'src/components/image/CustomImage'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import ActionSheetModal from 'src/components/modal/ActionSheetModal'
import { CommonToast, ShowLoading, DismissLoading } from 'src/utils/ToastUtil'
import { ServiceTelephone } from 'src/config/index'
import { CustomCallPhone } from 'src/utils/PermissionsUtil'
import { getMasterSearch, getOperatorApplyOperator } from 'src/utils/RequestAPI'

import { connect } from 'react-redux'
import { DO_REQUEST_MAIN_PAGE_B_ACTION } from 'src/pageB/main/main-page/store/action'
import { UPDATE_USERINFO_ACTION } from 'src/store/actions/userinfo'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  doRequestUserCompanyApplyApply (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, BMineCenterStore }) => ({
    userId: userinfo.B.userId,
    haveCompanyApply: BMineCenterStore.haveCompanyApply
  }),
  mapDispatchToProps
)
class BCompanyApplyJoin extends BasePage {
  constructor (props) {
    super(props)
    const { joinCompany, companyName, companyId } = this.configState()
    this.state = {
      header: {},
      masterData: {},
      moreSelectShow: false,
      retrieveSelectShow: false,
      joinCompany,
      companyName,
      companyId
    }
    this.getMasterSearchRequest(companyId)
  }

  selectArrRetrieve = [
    {
      value: 0,
      label: '137-2863-1695'
    }
  ]

  selectArrMore = [
    {
      value: 0,
      label: '切换为求职者'
    }
  ]

  configState = () => {
    const {
      navigation: {
        state: { params }
      },
      haveCompanyApply
    } = this.props
    let joinCompany // 创建公司  本页面是加入公司
    let companyName
    let companyId
    this.selectArrMore = [
      {
        value: 0,
        label: '切换为求职者'
      }
    ]
    if (params && !params.disable) {
      joinCompany = true
      companyName = params.companyName
      companyId = params.companyId
    } else if (haveCompanyApply.type === 'operator') {
      joinCompany = false
      companyName = haveCompanyApply.companyName
      companyId = haveCompanyApply.companyId
      this.selectArrMore = [
        {
          value: 0,
          label: '切换为求职者'
        },
        {
          value: 1,
          label: '更换企业'
        }
      ]
      if (haveCompanyApply.type === 0) {
        // 审核未通过
        this.goBack()
      } else if (haveCompanyApply.type === 1) {
        // 审核通过
        this.goBack()
      } else if (haveCompanyApply.type === 2) {
        // 审核中
        this.refreshApplyState()
      }
    }
    return {
      companyId,
      joinCompany,
      companyName
    }
  }

  componentWillUnmount () {
    super.componentWillUnmount()
    this.clearRefreshTimer()
  }

  refreshApplyState = (dealy = 15000) => {
    this.clearRefreshTimer()
    this.refreshTimer = setTimeout(() => {
      const {
        userId
      } = this.props
      this.props.doRequestUserCompanyApplyApply({ userId }).finally(() => {
        const { joinCompany } = this.configState()
        this.setState({
          joinCompany
        })
      })
    }, dealy)
  }

  clearRefreshTimer = () => {
    this.refreshTimer && clearTimeout(this.refreshTimer)
    this.refreshTimer = null
  }

  getMasterSearchRequest = companyId => {
    getMasterSearch({
      params: {
        companyId
      }
    }).then(res => {
      this.setState({
        masterData: res.data
      })
    })
  }

  childRender () {
    const {
      moreSelectShow,
      retrieveSelectShow,
      companyName,
      masterData: { userName, mobile, postion },
      joinCompany
    } = this.state
    return (
      <Fragment>
        <ScrollView
          style={styles.container}
          keyboardShouldPersistTaps="handled"
        >
          <Text style={styles.companyName}>{companyName}</Text>
          <View style={styles.materWrap}>
            <Text style={styles.masterTxt1}>{userName}</Text>
          </View>
          <View style={[styles.materWrap, { marginTop: 0 }]}>
            <Text style={styles.masterTxt1}>{postion}</Text>
            <View style={styles.line} />
            <Text style={styles.masterTxt1}>{mobile}</Text>
          </View>
        </ScrollView>
        {joinCompany && (
          <View style={styles.btnsWrap}>
            <CustomButton onPress={this.companyJoinClick}>
              <CustomBoxShadow style={styles.shadowWrap}>
                <View style={styles.shadowCont}>

                  <Text style={styles.shadowTxt}>
                  企业被创建，<Text style={styles.yellow}>申请加入</Text>
                  </Text>
                  <CustomImage
                    source={require('@/imgC/company/yellow-join.png')}
                  />
                  <View style={styles.flex1} />
                  <CustomImage
                    style={styles.arrow}
                    source={require('@/imgC/company/yellow-arrow.png')}
                  />
                </View>

              </CustomBoxShadow>
            </CustomButton>
            <CustomButton onPress={this.companyRetrieveClick}>
              <CustomBoxShadow style={styles.shadowWrap}>
                <View style={styles.shadowCont}>
                  <Text style={styles.shadowTxt}>
                  企业被冒用，
                    <Text style={styles.yellow}>联系客服</Text>
                  </Text>
                  <CustomImage
                    source={require('@/imgC/company/yellow-service.png')}
                  />
                  <View style={styles.flex1} />
                  <CustomImage
                    style={styles.arrow}
                    source={require('@/imgC/company/yellow-arrow.png')}
                  />
                </View>

              </CustomBoxShadow>
            </CustomButton>
          </View>
        )}
        {!joinCompany && (
          <View style={styles.joiningWrap}>
            <Text style={styles.joiningTip}>
              {
                '已通知该企业管理员，等待管理员通过。 \n您也可以联系您的管理员请求快速通过。'
              }
            </Text>
            <Text style={styles.tipTel} onPress={this.callPhone}>
              客服热线： <Text style={styles.tipTelYellow}>{ServiceTelephone}</Text>
            </Text>
            <NextButton
              style={styles.nextButton}
              title="申请中..."
              enable={false}
            />
          </View>
        )}
        <ActionSheetModal
          visible={moreSelectShow}
          onCancel={this._moreActionSheetModalCancel}
          selectClick={this._moreActionSheetModalClick}
          onModalHide={this._moreActionSheetModalHide}
          titleText={'更多'}
          selectArr={this.selectArrMore}
        />
        <ActionSheetModal
          visible={retrieveSelectShow}
          onCancel={this._retrieveActionSheetModalCancel}
          selectClick={this._retrieveActionSheetModalClick}
          onModalHide={this._retrieveActionSheetModalHide}
          titleText={'联系客服'}
          selectArr={this.selectArrRetrieve}
        />
      </Fragment>
    )
  }

  renderNavigationBarChild () {
    return (
      <CustomButton style={styles.moreBtn} onPress={this._showMoreActionSheetModal}>
        <Text style={styles.moreText}>更多</Text>
      </CustomButton>
    )
  }

  toggleModal = (selectShow, value) => {
    this.setState({
      [selectShow]: value
    })
  }

  /* more选择 picker */
  _showMoreActionSheetModal = () => {
    this.toggleModal('moreSelectShow', true)
  }

  _moreActionSheetModalCancel = () => {
    this.toggleModal('moreSelectShow', false)
  }

  _moreActionSheetModalClick = () => {
    this.toggleModal('moreSelectShow', false)
  }

  _moreActionSheetModalHide = index => {
    if (!index) {
      return
    }
    const { navigation, updateUserInfo } = this.props
    switch (this.selectArrMore[index - 1].value) {
      case 0:
        console.log('切换为求职者')
        updateUserInfo({
          role: 'C'
        })
        navigation.navigate('CMainNavigator')
        break
      case 1:
        navigation.replace('BCompanyApplyName')
        break
      default:
        break
    }
  }

  /* 找回 picker */
  companyRetrieveClick = () => {
    this.toggleModal('retrieveSelectShow', true)
  }

  _retrieveActionSheetModalCancel = () => {
    this.toggleModal('retrieveSelectShow', false)
  }

  _retrieveActionSheetModalClick = () => {
    this.toggleModal('retrieveSelectShow', false)
  }

  _retrieveActionSheetModalHide = () => {
    // todo 打电话 selectArrRetrieve137-2863-1695
  }

  companyJoinClick = () => {
    const { companyId } = this.state
    const { userId } = this.props
    const params = {
      userId
    }
    const headers = {
      companyId
    }
    ShowLoading()
    getOperatorApplyOperator({ headers, params })
      .then(res => {
        this.props.navigation.setParams({ disable: true })
        return this.props.doRequestUserCompanyApplyApply({ userId })
      }).then(() => {
        const { joinCompany } = this.configState()
        this.setState({
          joinCompany
        })
      }).finally(() => {
        DismissLoading()
      })
  }

  callPhone = () => {
    CustomCallPhone(ServiceTelephone)
  }
}
export default BCompanyApplyJoin
const styles = StyleSheet.create({
  flex1: {
    flex: 1
  },
  container: {
    flex: 1,
    marginBottom: ScaleS(106),
    marginHorizontal: ScaleS(20)
  },
  moreBtn: {
    alignSelf: 'flex-end',
    marginRight: ScaleS(20),
    width: ScaleS(58),
    height: ScaleS(28),
    borderRadius: ScaleS(14),
    borderStyle: 'solid',
    borderColor: '#000000',
    borderWidth: ONE_PIXEL,
    justifyContent: 'center',
    alignItems: 'center'
  },
  moreText: {
    color: '#000000',
    fontSize: ScaleT(12),
    fontWeight: '600'
  },
  companyName: {
    marginVertical: ScaleS(10),
    fontSize: ScaleT(27),
    fontWeight: '500',
    color: '#000000',
    lineHeight: ScaleS(47)
  },
  materWrap: {
    marginTop: ScaleS(28),
    height: ScaleS(40),
    flexDirection: 'row',
    alignItems: 'center'
  },
  masterTxt1: {
    fontSize: ScaleT(16),
    fontWeight: '400',
    color: '#444444'
  },
  line: {
    marginHorizontal: ScaleS(18),
    width: ONE_PIXEL,
    height: ScaleS(13),
    backgroundColor: '#444444'
  },
  btnsWrap: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    paddingHorizontal: ScaleS(20),
    paddingVertical: ScaleS(10)
  },
  shadowWrap: {
    width: ScaleS(335),
    height: ScaleS(70),
    backgroundColor: '#ffffff',
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.25,
    shadowColor: '#9C9C9C',
    borderRadius: ScaleS(10),
    marginVertical: ScaleS(10),
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    }
  },
  shadowCont: {
    width: ScaleS(335),
    height: ScaleS(70),
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: ScaleS(18),
    paddingRight: ScaleS(22)
  },
  shadowTxt: {
    fontSize: ScaleT(20),
    fontWeight: '500',
    color: '#444444',
    marginRight: ScaleS(6)
  },
  yellow: {
    color: '#FFC200'
  },
  arrow: {
    marginRight: 0
  },
  joiningWrap: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    alignItems: 'center'
  },
  joiningTip: {
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#444444',
    lineHeight: ScaleS(29),
    textAlign: 'center'
  },
  tipTel: {
    marginTop: ScaleS(44),
    fontSize: ScaleT(13),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  tipTelYellow: { textDecorationLine: 'underline', color: '#FFC200' },
  nextButton: {
    marginTop: ScaleS(10),
    marginBottom: ScaleS(20)
  }
})
